<?php


namespace App\Http\Controllers\Admin;


use App\Http\Controllers\Controller;
use App\Model\Product;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;

class ProductController extends Controller
{
    /**
     * 后台产品列表
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(){
        $product = Product::paginate(10);
        return JsonResponse(200,true,'获取成功',$product);
    }

    /**
     * 添加产品
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function add(Request $request){
        $insert = $request->post();
        $insert['created_at'] = time();
        $insert['updated_at'] = time();
        $result = DB::table('product')
            ->insert($insert);
        return JsonResponse(200,true,'添加成功',$result,$insert);
    }

    public function detail($id){
        $detail = DB::table('product')
            ->where('id',$id)
            ->first();
        if ($detail){
            return JsonResponse(200,true,'获取成功',$detail);
        }else{
            return JsonResponse(3001,false,'无此数据');
        }
    }

    public function edit(Request $request){
        $data = $request->post();
        $data['created_at'] = strtotime($data['created_at']);
        $data['updated_at'] = time();
        $edit = Product::where('id',$data['id'])
            ->update($data);
        if ($edit){
            return JsonResponse(200,true,'编辑成功');
        }else{
            return JsonResponse(3000,false,'编辑失败');
        }
    }

    public function delete($id){
        $detail = DB::table('product')
            ->where('id',$id)
            ->first();
        if ($detail){
            DB::beginTransaction();
            $disk = Storage::disk('local');
            $image_result = $disk->delete($detail->product_image);
            $product_result = DB::table('product')
                ->where('id',$id)
                ->delete();
            if ($image_result && $product_result){
                DB::commit();
                return JsonResponse(200,true,'删除成功');
            }else{
                DB::rollBack();
                return JsonResponse(1001,false,'删除失败', $image_result, $product_result);
            }
        }else{
            return JsonResponse(3001,false,'无此数据');
        }
    }
}
